#from __future__ import (absolute_import, division, print_function, unicode_literals)

import datetime  # For datetime objects
import os.path  # To manage paths
import sys  # To find out the script name (in argv[0])

# Import the backtrader platform
import backtrader as bt


# Create a Stratey
class TestStrategy(bt.Strategy):

    def log(self, txt, dt=None):
        ''' Logging function fot this strategy'''
        dt = dt or self.datas[0].datetime.date(0)
        print('%s, %s' % (dt.isoformat(), txt))

    def __init__(self):
        # Keep a reference to the "close" line in the data[0] dataseries
        self.dataclose = self.datas[0].close

        # To keep track of pending orders
        self.order = None

    def notify_order(self, order):
        if order.status in [order.Submitted, order.Accepted]:
            # Buy/Sell order submitted/accepted to/by broker - Nothing to do
            return

        # Check if an order has been completed
        # Attention: broker could reject order if not enough cash
        if order.status in [order.Completed]:
            if order.isbuy():
                self.log('BUY EXECUTED, %.2f' % order.executed.price)
            elif order.issell():
                self.log('SELL EXECUTED, %.2f' % order.executed.price)

            self.bar_executed = len(self)

        elif order.status in [order.Canceled, order.Margin, order.Rejected]:
            self.log('Order Canceled/Margin/Rejected')

        # Write down: no pending order
        self.order = None

    def next(self):
        # Simply log the closing price of the series from the reference
        self.log('Close, %.2f' % self.dataclose[0])

        if self.dataclose[0] < self.dataclose[-1]:
                if self.dataclose[-1] < self.dataclose[-2]:
                #if True:
                    self.log('BUY CREATE, %.2f' % self.dataclose[0])
                    self.order = self.buy()
        if self.dataclose[0] > self.dataclose[-1]:
                #if self.dataclose[-1] > self.dataclose[-2]:
                if True:
                    self.log('SELL CREATE, %.2f' % self.dataclose[0])
                    self.order = self.sell()
        #else:
        #    # Already in the market ... we might sell
        #    if self.position and len(self) >= (self.bar_executed + 5):
        #        # SELL, SELL, SELL!!! (with all possible default parameters)
        #        self.log('SELL CREATE, %.2f' % self.dataclose[0])

        #        # Keep track of the created order to avoid a 2nd order
        #        self.order = self.sell()


if __name__ == '__main__':
    # Create a cerebro entity
    cerebro = bt.Cerebro()

    # Add a strategy
    cerebro.addstrategy(TestStrategy)

    # Datas are in a subfolder of the samples. Need to find where the script is
    # because it could have been called from anywhere
    #modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
    #datapath = os.path.join(modpath, '../../datas/orcl-1995-2014.txt')

    # Create a Data Feed
    #data = bt.feeds.YahooFinanceCSVData
    #data = bt.feeds.YahooFinanceData(
    #    #dataname=datapath,
    #    dataname='AAPL',
    #    # Do not pass values before this date
    #    fromdate=datetime.datetime(2020, 1, 1),
    #    # Do not pass values before this date
    #    todate=datetime.datetime(2022, 5, 1),
    #    # Do not pass values after this date
    #    reverse=False)
    import tushare as ts
    import pandas as pd
    # tushare

    def get_single_kdata(code, start='2019-01-01', end='2022-05-01', index=False,freq='D'):
        #with open('../tools/token.tmp', 'r') as file:
        #  _token = file.read().replace('\n', '').strip()
        #  print('token',_token)
        #  ts.set_token(_token)
        #df = ts.pro.get_k_data(code, autype='qfq', start=start, end=end, index=index)
        df = ts.pro_bar(ts_code=code, adj='qfq', freq=freq, start_date=start, end_date=end)
        #print('df=',df)
        df['openinterest'] = 0
        df['date'] = pd.to_datetime(df['trade_date'])
        df['volume']=df['vol']
        df.index = pd.to_datetime(df['trade_date'])
        #return df[['date', 'open', 'high', 'low', 'close', 'volume', 'openinterest']]
        rt = df[['date', 'open', 'high', 'low', 'close', 'volume', 'openinterest']]
        print('rt=',rt)
        rt = rt.sort_index(ascending=True)
        return rt

    # TODO https://zhuanlan.zhihu.com/p/401910154

    df = get_single_kdata('000725.SZ')
    data = bt.feeds.PandasData(dataname=df)

    # Add the Data Feed to Cerebro
    cerebro.adddata(data)

    # Set our desired cash start
    cerebro.broker.setcash(100000.0)

    # Print out the starting conditions
    print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())

    # Run over everything
    cerebro.run()

    # Print out the final result
    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())

    # Plot the result
    #cerebro.plot(style='bar')
    cerebro.plot()
